package logic

import (
	"account-register/accountrpc/accountrpc"
	"account-register/accountrpc/internal/svc"
	"account-register/mobels/cache"
	"account-register/mobels/mysql"
	"account-register/pkg"
	"context"
	"fmt"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserRegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserRegisterLogic {
	return &UserRegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserRegisterLogic) UserRegister(in *accountrpc.UserRegisterRequest) (*accountrpc.UserRegisterResponse, error) {
	// todo: add your logic here and delete this line

	sms := cache.Rdb.Get(l.ctx, "sendSms"+"register"+in.Mobile)
	//image := cache.Rdb.Get(l.ctx, "captcha"+"register"+in.Mobile)

	if sms.Val() != in.CodeSms {
		return nil, fmt.Errorf("短信验证码错误，请重新输入")
	}
	/*if image.Val() != in.Captcha {
		return nil, fmt.Errorf("图形验证码错误，请重新输入")
	}*/

	var user mysql.User
	user = mysql.User{
		Mobile:   in.Mobile,
		Password: pkg.Md5(in.Password),
	}
	err := mysql.DB.Create(&user).Error
	if err != nil {
		return nil, fmt.Errorf("注册失败")
	}

	//注册成功后删除验证码 返回id
	cache.Rdb.Del(l.ctx, "sendSms"+"register"+in.Mobile)
	//cache.Rdb.Del(l.ctx, "captcha"+"register"+in.Mobile)
	return &accountrpc.UserRegisterResponse{Id: int64(user.ID)}, nil
}
